/*
 * Copyright 2007 Matt Jensen
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
package org.jtell.spring;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jtell.JTell;
import org.jtell.JTellContext;
import org.jtell.JTellContextBuilder;
import org.jtell.config.ConfigurationSource;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.AbstractFactoryBean;

/**
 * <p>
 * <code>JTellContextFactoryBean</code> is an implementation of the Spring {@link FactoryBean} interface which creates
 * and configures a {@link JTellContext} instance.
 * </p>
 */
public class JTellContextFactoryBean extends AbstractFactoryBean
{
    private static Log LOG = LogFactory.getLog(JTellContextFactoryBean.class);

    /**
     * <p>
     * The configuration source.
     * </p>
     */
    private ConfigurationSource m_configurationSource;

    /**
     * <p>
     * Construct a {@link JTellContextFactoryBean} instance.
     * </p>
     */
    public JTellContextFactoryBean()
    {
        super();
    }

    /* inherit javadoc */
    @Override
    public Class getObjectType()
    {
        return JTellContext.class;
    }

    /**
     * <p>
     * Set the configuration source.
     * </p>
     *
     * @param configurationSource the configuration source.
     */
    public void setConfigurationSource(ConfigurationSource configurationSource)
    {
        m_configurationSource = configurationSource;
    }

    /* inherit javadoc */
    @Override
    protected Object createInstance() throws Exception
    {
        // Configure the context.
        final JTellContextBuilder builder = JTell.buildContext();
        ContextUtils.applyBasicSetup(builder);
        if (null != m_configurationSource)
        {
            builder.setConfigurationSource(m_configurationSource);
        }

        // Create and return the context.
        final JTellContext result = builder.createContext();
        if (LOG.isDebugEnabled())
        {
            LOG.debug(String.format("Returning new context [%s].", result));
        }
        return result;
    }
}
